package com.sc.user.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.common.domain.Result;
import com.sc.common.enums.HttpCodeEnum;
import com.sc.common.util.JwtUtil;
import com.sc.user.config.JwtProperties;
import com.sc.user.domain.dto.LoginDto;
import com.sc.user.domain.pojo.ApUser;
import com.sc.user.service.ApUserService;
import com.sc.user.mapper.ApUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author Lenovo
 * @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
 * @createDate 2025-09-08 15:42:52
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>
        implements ApUserService {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public Result login(LoginDto loginDto) {
        //1.数据校验
        if (StringUtils.isBlank(loginDto.getPhone())
                || StringUtils.isBlank(loginDto.getPassword())) {
            HashMap<String, Object> id = new HashMap<>();
            id.put("id", 1);
            String jwt = JwtUtil.createJWT(jwtProperties.getSecret(), jwtProperties.getTimeout(), id);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", jwt);
            return Result.success(map);
        }
        //2.查询数据库
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone, loginDto.getPhone());
        ApUser user = getOne(wrapper);
        if (user == null)
            return Result.error(HttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
        //3.比对密码
        String pwd = DigestUtil.md5Hex(loginDto.getPassword() + user.getSalt());
        if (!pwd.equals(user.getPassword()))
            return Result.error(HttpCodeEnum.LOGIN_PASSWORD_ERROR);
        //返回数据 jwt+user
        HashMap<String, Object> id = new HashMap<>();
        id.put("id", user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getSecret(),
                jwtProperties.getTimeout(), id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        user.setSalt("");
        user.setPassword("");
        map.put("user", user);
        return Result.success(map);
    }
}




